package com.ld.collegetask.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.ld.collegetask.DynamicMemberReleaseActivity;
import com.ld.collegetask.R;
import com.ld.collegetask.beans.BaseJsonBean;
import com.ld.collegetask.beans.DynamicBean;
import com.ld.collegetask.beans.DynamicListBean;
import com.ld.collegetask.databinding.FragmentDynamicBinding;
import com.ld.collegetask.login.LoginActivity;
import com.ld.collegetask.serverInterface.RequestSerives;
import com.ld.collegetask.utils.AppApplication;
import com.ld.collegetask.utils.SharePreference;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class DynamicFragment extends BaseFragment implements View.OnClickListener{

    private static DynamicFragment dynamicFragment;

    private View view;
    private FragmentDynamicBinding binding;
    private ImageView dynamic_member_release_button;
    private Activity mActivity;

    private Integer schoolId = 0;
    private Integer pageNo = 0;
    private Integer totalPage = 0;
    private SharePreference sp;

    public DynamicFragment() {
    }

    public static DynamicFragment getInstance() {
        if (dynamicFragment == null) {
            dynamicFragment = new DynamicFragment();
        }
        return dynamicFragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_dynamic, container, false);
        view = binding.getRoot();
        mActivity = getActivity();

        setTitleView(mActivity,binding.ilTitle,false,true,false,true);
        setLoadingView(mActivity,binding.ilLoading);
        setTitle("说说");
        setIco(R.drawable.order_release_button);

        sp = new SharePreference(mActivity);

        loading_go();

        // 设置颜色属性的时候一定要注意是引用了资源文件还是直接设置16进制的颜色，因为都是int值容易搞混
        // 设置下拉进度的背景颜色，默认就是白色的
        binding.swipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        // 设置下拉进度的主题颜色
        binding.swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.colorPrimaryDark);

        // 下拉时触发SwipeRefreshLayout的下拉动画，动画完毕之后就会回调这个方法
        binding.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                ContentList.clear();
                pageNo = 0;
                totalPage = 0;
                dynamic_member_list();
            }
        });
        return view;
    }

    @Override
    public void loading() {
        ContentList.clear();
        pageNo = 0;
        totalPage = 0;
        dynamic_member_list();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        findView();
    }

    public void findView() {
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:                                                 //条目点击
                if (resultCode == 1){
                    ContentList.clear();
                    pageNo = 0;
                    totalPage = 0;
                    dynamic_member_list();
                }else{
                }
                break;
            case 2:                                                 //发布点击
                if (resultCode == 1){
                    ContentList.clear();
                    pageNo = 0;
                    totalPage = 0;
                    dynamic_member_list();
                }else{
                }
                break;
        }
    }

    private void dynamic_member_list() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<String> call = requestSerives.dynamic_member_list(null,null,pageNo);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(response.body().toString(), BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    DynamicListBean dynamicList = gson.fromJson(base.getJson(), DynamicListBean.class);
                    pageNo = dynamicList.getPageNo();
                    totalPage = dynamicList.getTotalPage();
                    ContentList.addAll(dynamicList.getDynamicList());
                    setListAdapter(ContentList);
                    loading_end();
                } else {
                    loading_error();
                }
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 加载完数据设置为不刷新状态，将下拉进度收起来
                        binding.swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 加载完数据设置为不刷新状态，将下拉进度收起来
                        binding.swipeRefreshLayout.setRefreshing(false);
                    }
                });
                loading_error();
            }
        });
    }

    private DynamicListBean dynamicListBean;
    private List<DynamicBean> ContentList = new ArrayList<>();
    private DynamicFragment.MyListAdapter<DynamicBean> adapter;

    private void setListAdapter(List<DynamicBean> list) {
        if (pageNo <= 1) {
            adapter = new DynamicFragment.MyListAdapter<>(getActivity(), list, R.layout.fragment_dynamic_listitem, com.ld.collegetask.BR.dynamicBean);
            binding.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }


    public class MyListAdapter<T> extends BaseAdapter {
        private Context context;//上下文环境
        private List<T> list;//通用的，不知道数据
        private int layoutId;//通用的，不知道布局
        private int variableId;//变量的id

        // 通过构造器关联数据源与数据适配器
        public MyListAdapter(Context context, List<T> list, int layoutId, int variableId) {
            this.context = context;
            this.list = list;
            this.layoutId = layoutId;
            this.variableId = variableId;
        }

        @Override
        public int getCount() {
            if (list != null)
                return list.size();
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (position == list.size() - 1) {
                if (pageNo < totalPage) {
                    pageNo++;
                    dynamic_member_list();
                }
            }

            ViewDataBinding viewDataBinding = null;
            if (convertView == null) {// View未被实例化，即缓冲池中无缓存才创建View
                viewDataBinding = DataBindingUtil.inflate(LayoutInflater.from(context), layoutId, parent, false);
            } else {
                viewDataBinding = DataBindingUtil.getBinding(convertView);
            }
            viewDataBinding.setVariable(variableId, list.get(position));
            return viewDataBinding.getRoot();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.tv_head_ico:                                  //发布说说
                if (sp.getLoginState()) {
                    startActivityForResult(new Intent(getActivity(), DynamicMemberReleaseActivity.class), 2);
                }else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
        }
    }
}
